package com.mrjy.video.bo;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.mrjy.common.entity.CoursePackageVideoRel;
import com.mrjy.common.entity.CustomModule;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.SubscriptionInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserVideoRel;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.entity.VideoInfoTypeRel;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.PolyvTokenUtil;
import com.mrjy.common.util.PolyvUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.SolrUtil;
import com.mrjy.coursepackage.dao.ICoursePackageVideoRelDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.custom.bo.ICustomModuleBo;
import com.mrjy.custom.dao.ICustomModuleDao;
import com.mrjy.custom.dto.CustomModuleDto;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.ISubscriptionInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.video.dao.IUserVideoRelDao;
import com.mrjy.video.dao.IVideoInfoDao;
import com.mrjy.video.dao.IVideoInfoTypeRelDao;
import com.mrjy.wechat.conts.WxConsts;
import com.tencent.common.Util;



@Service("videoInfoBo")
public class VideoInfoBo implements IVideoInfoBo {
	
	@Resource
	private IVideoInfoDao videoInfoDao;
	@Resource
	private IVideoInfoTypeRelDao videoInfoTypeRelDao;
	@Resource
	private IUserVideoRelDao userVideoRelDao;
	@Resource
	private IUserVideoRelBo userVideoRelBo;
	@Autowired
	private RedisPool redisPool;
	@Autowired
	private ICustomModuleBo customModuleBo;
	@Autowired
	private ICustomModuleDao customModuleDao;
	@Autowired
	private SolrServerClient solrServerClient;
	@Autowired
	private IUserInfoDao userInfoDao;
    @Autowired
    private IMessageInfoDao messageInfoDao;
    @Autowired
    private ISubscriptionInfoDao subscriptionInfoDao;
    @Resource
    private ICoursePackageVideoRelDao coursePackageVideoRelDao;
    
    
    private Logger LOGGER = LoggerFactory.getLogger(VideoInfoBo.class);


    @Override
    public Object txInsert(Object object,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (null == loginUser) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户未登录");
//            return map;
//        }
        if(null == object){
			map.put("err_code", -1);
			map.put("err_msg", "传入参数为空");
			return map;
		}
		VideoInfo videoInfo = (VideoInfo)object;
		//数据校验
		if (StringUtils.isBlank(videoInfo.getVideoName())) {
			map.put("err_code", 400);
			map.put("err_msg", "视频名称不能为空");
			return map;
		}
		if (videoInfo.getVideoName().length()>50) {
			map.put("err_code", 401);
			map.put("err_msg", "视频名称不能超过50个字符");
			return map;
		}
        if (StringUtils.isBlank(videoInfo.getAudioCode())) {
            videoInfo.setAudioCode(null);
        }
        if (StringUtils.isBlank(videoInfo.getVideoCode())) {
            videoInfo.setVideoCode(null);
        }
        videoInfo.setOriginalVideoName(videoInfo.getVideoName());
        if (StringUtils.isNotBlank(videoInfo.getVideoDesc()) &&
                videoInfo.getVideoDesc().length()>240) {
			map.put("err_code", 403);
			map.put("err_msg", "视频简介不能超过240个字符");
			return map;
		}
//		if (videoInfo.getTypeIds()==null||videoInfo.getTypeIds().length==0) {
//			map.put("err_code", 404);
//			map.put("err_msg", "视频标签不能为空");
//			return map;
//		}
		if (videoInfo.getTypeIds() != null && videoInfo.getTypeIds().length>10) {
			map.put("err_code", 405);
			map.put("err_msg", "视频标签不能超过10个");
			return map;
		}
		if (videoInfo.getUserId()==null||videoInfo.getUserId()<=0) {
			map.put("err_code", 406);
			map.put("err_msg", "讲师不能为空");
			return map;
        }
		if (StringUtils.isBlank(videoInfo.getIsSpecial())) {
			map.put("err_code", 409);
			map.put("err_msg", "请选择微课类型");
			return map;
		}
        videoInfo.setCreateTime(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置了发布时间,则将release_flag置为1  (0:已发布   1:未发布)
        if (StringUtils.isNotBlank(videoInfo.getReleaseTimeString())) {
  			String format = sdf.format(new Date(System.currentTimeMillis()));
            if (StringUtils.isBlank(videoInfo.getReleaseTimeString()) &&
                    !DateUtil.compareTime(videoInfo.getReleaseTimeString(), format).equals("surpass")) { //发布时间必须是未来的时间
                map.put("err_code", 407);
  				map.put("err_msg", "发布时间必须大于当前系统时间");
  				return map;
			}
  			videoInfo.setReleaseFlag(1);
  			videoInfo.setReleaseTime(new Timestamp(DateUtil.stringToLong(videoInfo.getReleaseTimeString(), DateUtil.FULL_DATE)));
  		}else {
  			videoInfo.setReleaseFlag(0);
  			videoInfo.setReleaseTime(new Timestamp(videoInfo.getCreateTime()));
  		}
        if (StringUtils.isNotBlank(videoInfo.getAnnouncementTimeStr()) && videoInfo.getAnnouncementFlag() == 1) {
            String format = sdf.format(videoInfo.getReleaseTime());
            if (!DateUtil.compareTime(videoInfo.getAnnouncementTimeStr(), format).equals("surpass")) { //通知时间必须是未来的时间
                map.put("err_code", 407);
                map.put("err_msg", "通知时间必须大于发布时间");
                return map;
            }
            videoInfo.setAnnouncementTime(new Timestamp(DateUtil.stringToLong(videoInfo.getAnnouncementTimeStr(), DateUtil.FULL_DATE)));
        }


        videoInfo.setUpdateTime(new Date().getTime());
		videoInfo.setCommentNum(0);//默认0
		videoInfo.setPlayTimes(0);//
		if (videoInfo.getOriginalPrice() == 0) {
			videoInfo.setFreeFlag(1); //免费
		}else {
			videoInfo.setFreeFlag(0); //收费
		}
        videoInfo.setHotFlag(0);

        if (StringUtils.isBlank(videoInfo.getAudioCode()) && StringUtils.isBlank(videoInfo.getVideoCode())) {
            map.put("err_code", 408);
            map.put("err_msg", "音频与视频不能同时为空");
            return map;
        }
        int count = videoInfoDao.insert(videoInfo);//插入信息表
        if(count > 0){
			try {
				//插入标签
				if (videoInfo.getTypeIds() != null && videoInfo.getTypeIds().length > 0) {
					insertByTypeIds(videoInfo.getTypeIds(),videoInfo.getId());
				}
				//添加缓存
				String polyInfoJson = "";
				PolyInfo polyInfo = new PolyInfo();
				PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(videoInfo.getVideoCode());
				PolyInfo polyInfoAudio = (PolyInfo) PolyvUtil.queryUrlByVid(videoInfo.getAudioCode());
				//封装成一个polyInfo
				if (polyInfoVideo!=null) {
					polyInfo.setMpvh(polyInfoVideo.getMpvh());
					polyInfo.setMpvl(polyInfoVideo.getMpvl());
					polyInfo.setMpvm(polyInfoVideo.getMpvm());
					polyInfo.setImgh(polyInfoVideo.getImgh());
					polyInfo.setImgl(polyInfoVideo.getImgl());
	                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
	                polyInfo.setHls_l(polyInfoVideo.getHls_l());
	                polyInfo.setHls_m(polyInfoVideo.getHls_m());
	                polyInfo.setHls_h(polyInfoVideo.getHls_h());
	                polyInfo.setSeed(polyInfoVideo.getSeed());
	                polyInfo.setDuration(polyInfoVideo.getDuration());
	            }
	            if (polyInfoAudio != null && polyInfoAudio.getMp3().indexOf(".mp3") > -1) {
	                polyInfo.setDuration(polyInfoAudio.getDuration());
					polyInfo.setMp3(polyInfoAudio.getMp3());
					polyInfo.setSourceFilesize(polyInfoAudio.getSourceFilesize());
					polyInfo.setTitle(polyInfoAudio.getTitle());
				}
				polyInfoJson = JSONObject.fromObject(polyInfo).toString();
				if (polyInfoJson!=null) {
					redisPool.set(GlobalConstant.VIDEO_POLYV_URL+videoInfo.getId(), JSONObject.fromObject(polyInfoJson).toString());
				}
				/*//单价传0则添加至免费试听
				if (videoInfo.getOriginalPrice() == 0d) {
					CustomModule module = new CustomModule();
					module.setCmType(2);
					module.setCmProgramId(videoInfo.getId());
					module.setCreateTime(new Timestamp(System.currentTimeMillis()));
					module.setDisableFlag(0);
					module.setCmName("免费试听");
					//查询最大的cm_sort
					int max_sort = customModuleDao.queryMaxSort();
					module.setCmSortOne(max_sort+1);
					customModuleDao.insertSelective(module);
				}*/
				if(videoInfo.getReleaseFlag() != 1){
					//添加索引
					SolrEntity entity = new SolrEntity();
					entity.setId("video_"+videoInfo.getId());
					entity.setVideoId(videoInfo.getId());
					entity.setVideoName(videoInfo.getVideoName());
					entity.setVideoDesc(videoInfo.getVideoDesc());
					entity.setVideoTypes(SolrUtil.formatVideoTypes(videoInfo.getTypeIds()));
					entity.setVideoTeacher(userInfoDao.queryById(videoInfo.getUserId()).getUserName());
					entity.setCoverUrl(videoInfo.getCoverUrl());
	        		solrServerClient.add(entity);
	        		map.put("solr_msg", "索引插入成功");
				}
            } catch (Exception e) {
        		e.printStackTrace();
        		LOGGER.debug("[索引插入失败]："+e.getMessage());
        		map.put("solr_msg", "索引插入失败");
        		map.put("err_code", 500);
        		map.put("err_msg", "添加视频失败");
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        		return map;
        	}
			map.put("err_code", 200);
			map.put("err_msg", "添加视频成功");
        }else{
			map.put("err_code", 500);
			map.put("err_msg", "添加视频失败");
		}
		return map;
	}
	
	private int insertByTypeIds(Integer[] typeIds,int videoInfoId){
		int count = 0;
		for(int typeId : typeIds){
			VideoInfoTypeRel infoTypeRel = new VideoInfoTypeRel();
			infoTypeRel.setTypeId(typeId);
			infoTypeRel.setVideoInfoId(videoInfoId);
			count += videoInfoTypeRelDao.insert(infoTypeRel);
		}
		return count;
	}
	@Override
	public Object txDeleteByIds(int[] ids) {
		try {
			return videoInfoDao.deleteByIds(ids);
		} catch (DataAccessException e) {
			return 0;
		}
	}
	
	@Override
	public Object txUpdateDisableFlag(Object object,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		VideoInfo videoInfo = (VideoInfo)object;
		if (videoInfo.getIds()==null||videoInfo.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		int result = videoInfoDao.updateDisableFlag(videoInfo);
		if(result > 0){
			if (videoInfo.getDisableFlag().intValue() == 0) {
				//数据库启用,添加视频索引
				try {
					VideoInfo video = null;
					for (Integer id : videoInfo.getIds()) {
						SolrEntity videoEntity = new SolrEntity();
						video = (VideoInfo) videoInfoDao.queryById(id);
						videoEntity.setId("video_"+id);
						videoEntity.setVideoId(id);
						videoEntity.setVideoName(video.getVideoName());
						videoEntity.setVideoDesc(video.getVideoDesc());
						videoEntity.setVideoTypes(video.getTypeName());
						videoEntity.setVideoTeacher(video.getUserName());
	                	solrServerClient.add(videoEntity);
					}
					map.put("solr_msg", "索引添加成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引添加失败]："+e.getMessage());
					map.put("solr_msg", "索引添加失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}else if (videoInfo.getDisableFlag().intValue() == 1) {
				//数据库禁用,要删除索引
				try {
					for (Integer id : videoInfo.getIds()) {
						solrServerClient.deleteById("video_"+id);
					}
					map.put("solr_msg", "索引删除成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引删除失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+result+"条记录受影响");
		}else{
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+result+"条记录受影响");
		}
		return map;
	}

	@Override
	public Object txUpdateById(Object object,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		VideoInfo videoInfo = (VideoInfo) object;
		//数据校验
		if (StringUtils.isBlank(videoInfo.getVideoName())) {
			map.put("err_code", 400);
			map.put("err_msg", "视频名称不能为空");
			return map;
		}
		if (videoInfo.getVideoName().length()>50) {
			map.put("err_code", 401);
			map.put("err_msg", "视频名称不能超过50个字符");
			return map;
		}
        if (StringUtils.isNotBlank(videoInfo.getVideoDesc()) &&
                videoInfo.getVideoDesc().length()>240) {
			map.put("err_code", 403);
			map.put("err_msg", "视频简介不能超过240个字符");
			return map;
		}
//		if (videoInfo.getTypeIds()==null||videoInfo.getTypeIds().length==0) {
//			map.put("err_code", 404);
//			map.put("err_msg", "视频标签不能为空");
//			return map;
//		}
		if (videoInfo.getTypeIds() != null && videoInfo.getTypeIds().length>10) {
			map.put("err_code", 405);
			map.put("err_msg", "视频标签不能超过10个");
			return map;
		}
		if (videoInfo.getUserId()==null||videoInfo.getUserId()<=0) {
			map.put("err_code", 406);
			map.put("err_msg", "讲师不能为空");
			return map;
		}
		if (StringUtils.isBlank(videoInfo.getIsSpecial())) {
			map.put("err_code", 409);
			map.put("err_msg", "请选择微课类型");
			return map;
		}
        if (StringUtils.isBlank(videoInfo.getAudioCode())) {
            videoInfo.setAudioCode(null);
        }
        if (StringUtils.isBlank(videoInfo.getVideoCode())) {
            videoInfo.setVideoCode(null);
        }
        VideoInfo videoInfo2 = (VideoInfo) queryById(videoInfo.getId()); 
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(videoInfo2.getReleaseFlag() == 1){//此时课程属于未发布
        	if (StringUtils.isNotBlank(videoInfo.getReleaseTimeString())) {
                String format = sdf.format(new Date(System.currentTimeMillis()));
                if (!DateUtil.compareTime(videoInfo.getReleaseTimeString(), format).equals("surpass")) { //通知时间必须是未来的时间
                    map.put("err_code", 407);
                    map.put("err_msg", "发布时间必须大于当前系统时间");
                    return map;
                }
                videoInfo.setReleaseTime(new Timestamp(DateUtil.stringToLong(videoInfo.getReleaseTimeString(), DateUtil.FULL_DATE)));
                videoInfo.setReleaseFlag(1);//设置发布状态
            }else{
            	videoInfo.setReleaseFlag(0);//设置发布状态
            	videoInfo.setReleaseTime(new Timestamp(DateUtil.stringToLong(sdf.format(new Date(System.currentTimeMillis())), DateUtil.FULL_DATE)));
            }
        }
        if(videoInfo.getAnnouncementFlag() == 1){//需要通知
        	if (StringUtils.isNotBlank(videoInfo.getAnnouncementTimeStr()) && videoInfo.getReleaseTime() != null) {
                String format = sdf.format(videoInfo.getReleaseTime());
                if (!DateUtil.compareTime(videoInfo.getAnnouncementTimeStr(), format).equals("surpass")) { //通知时间必须是未来的时间
                    map.put("err_code", 407);
                    map.put("err_msg", "通知时间必须大于发布时间");
                    return map;
                }
                videoInfo.setAnnouncementTime(new Timestamp(DateUtil.stringToLong(videoInfo.getAnnouncementTimeStr(), DateUtil.FULL_DATE)));
            } else if (StringUtils.isNotBlank(videoInfo.getAnnouncementTimeStr())) {
                String format = sdf.format(new Date(System.currentTimeMillis()));
                if (!DateUtil.compareTime(videoInfo.getAnnouncementTimeStr(), format).equals("surpass")) { //通知时间必须是未来的时间
                    map.put("err_code", 407);
                    map.put("err_msg", "通知时间必须大于当前时间");
                    return map;
                }
                videoInfo.setAnnouncementTime(new Timestamp(DateUtil.stringToLong(videoInfo.getAnnouncementTimeStr(), DateUtil.FULL_DATE)));
            }
        }
        
        int count = videoInfoDao.updateById(videoInfo);
        if (count > 0) {
			try {
				VideoInfo video = (VideoInfo) videoInfoDao.queryById(videoInfo.getId());
				//如果重新上传了视频, 则清除redis中该视频的缓存
                if (videoInfo.getVideoCode() != video.getVideoCode() || videoInfo.getAudioCode() != video.getAudioCode()) {
                    redisPool.del(GlobalConstant.VIDEO_POLYV_URL+videoInfo.getId());
				}
				//先把之前的记录删掉，再重新插入
				videoInfoTypeRelDao.deleteByVideoInfoId(videoInfo.getId());
				if (videoInfo.getTypeIds() != null && videoInfo.getTypeIds().length > 0) {
					insertByTypeIds(videoInfo.getTypeIds(),videoInfo.getId());
				}
				
				//如果单价改为大于0,则要禁用免费试听
				CustomModuleDto dto = new CustomModuleDto();
				dto.setCmProgramId(videoInfo.getId());
				dto.setCmType(2);
				if (videoInfo.getOriginalPrice() > 0d) {
					dto.setDisableFlag(1);
					customModuleDao.updateByProgramIdAndType(dto);
				//如果单价改为0,则视频添加至免费试听
				}else if (videoInfo.getOriginalPrice() == 0d) {
					//查询是否已存在相关记录
					List<CustomModuleDto> list = customModuleDao.checkDuplicate(dto);
					if (list!=null && list.size()>0) { //已存在记录,启用
						dto.setDisableFlag(0);
						customModuleDao.updateByProgramIdAndType(dto);
					}else {
						CustomModule module = new CustomModule();
						module.setCmType(2);
						module.setCmProgramId(videoInfo.getId());
						module.setCreateTime(new Timestamp(System.currentTimeMillis()));
						module.setDisableFlag(0);
						module.setCmName("免费试听");
						//查询最大的cm_sort
						int max_sort = customModuleDao.queryMaxSort();
						module.setCmSortOne(max_sort+1);
						customModuleDao.insertSelective(module);
					}
				}
				//更新索引
				SolrInputDocument document = new SolrInputDocument();
        		document.addField("id", "video_"+videoInfo.getId());
        		document.addField("videoId", videoInfo.getId());
        		document.addField("videoName", videoInfo.getVideoName());
        		document.addField("videoDesc", videoInfo.getVideoDesc());
        		document.addField("videoTypes", SolrUtil.formatVideoTypes(videoInfo.getTypeIds()));
        		document.addField("videoTeacher",  userInfoDao.queryById(videoInfo.getUserId()).getUserName());
        		document.addField("coverUrl", videoInfo.getCoverUrl());
        		solrServerClient.addDoc(document);
	    		map.put("solr_msg", "索引更新成功");
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    		LOGGER.debug("[索引更新失败]："+e.getMessage());
	    		map.put("solr_msg", "索引更新失败");
	    		map.put("err_code", 500);
	    		map.put("err_msg", "更新失败");
	    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return map;
	    	}
			map.put("err_code", 200);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object queryById(int id) {
		VideoInfo videoInfo = (VideoInfo) videoInfoDao.queryById(id);
		List<VideoInfoTypeRel> list = videoInfoTypeRelDao.selectListByVideoId(id);
		if (null != list && list.size() > 0) {
			Integer[] typeIds = new  Integer[list.size()];
			for (int i = 0; i < typeIds.length; i++) {
				VideoInfoTypeRel temp = list.get(i);
				if (null != temp) {
					typeIds[i] = temp.getTypeId();
				} 
			}
			videoInfo.setTypeIds(typeIds);
		}
		
		return videoInfo;
	}
	
	@Override
	public Object queryList(Object object) {
		return videoInfoDao.queryList(object);
	}
	
	@Deprecated
	@Override
	public Object queryPage(Object object,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", videoInfoDao.countList(object));
		map.put("rows", videoInfoDao.queryList(object));
		return map;
	}
	
	@Override
	public Object queryUrlByVideoId(Integer videoId, Integer userId) {		
		VideoInfo videoInfo = (VideoInfo) videoInfoDao.queryVideoByUserMember(videoId, userId);
		Map<String, Object> map = new HashMap<String, Object>();
        if (videoInfo != null) {
            PolyInfo polyInfo = (PolyInfo) PolyvUtil.queryUrlByVid(videoInfo.getVideoCode());
			map.put("id", videoInfo.getId());
			map.put("freeFlag", videoInfo.getFreeFlag());
			map.put("videoCode", videoInfo.getVideoCode());
			map.put("videoName", videoInfo.getVideoName());			
			map.put("teacherId", videoInfo.getUserId());
			map.put("teacherName",videoInfo.getUserName());
			map.put("teacherPic", videoInfo.getUserPic());
			map.put("teacherDesc", videoInfo.getUserDesc());
			map.put("picName", videoInfo.getPicName());
			map.put("mpvl", polyInfo.getMpvl());
			map.put("mpvm", polyInfo.getMpvm());
			map.put("mpvh", polyInfo.getMpvh());
			map.put("imgl", polyInfo.getImgl());
			map.put("imgh", polyInfo.getImgh());
            map.put("mpvFlag", polyInfo.getMpvFlag());
            return map;
        }else{
			return "error";
		}
	}
	
	@Override
	public Object queryVideoList(Object object) {
		return videoInfoDao.queryVideoList(object);
	}
	
	@Override
	public Object queryVideoPage(Object object) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", videoInfoDao.countVideoList(object));
		map.put("rows", videoInfoDao.queryVideoList(object));
		return map;
	}
	
	@Override
	public Object queryVideoListByFlag(VideoInfo videoInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == videoInfo){
			map.put("err_code", -1);
			map.put("err_msg", "传入对象不能为空");
			return map;
		}
		if(videoInfo.getUserId() != null && videoInfo.getUserId() == 0){
            videoInfo.setUserId(0);
        }

        if (videoInfo.getSortType().equals("notseen")) {
            SubscriptionInfo info = new SubscriptionInfo();
            info.setUserId(videoInfo.getUserId());
            info.setTypeId(1);
            List<SubscriptionInfo> subscriptionInfos = subscriptionInfoDao.queryByUserIdTeacherId(info);
            if (subscriptionInfos != null && subscriptionInfos.size() > 0) {
                SubscriptionInfo subscriptionInfo = subscriptionInfos.get(0);
                Integer disableFlag = subscriptionInfo.getDisableFlag();

                int isHasSub = disableFlag == 0 ? 1 : 0;
                map.put("isHasSub", isHasSub);
            } else {
                map.put("isHasSub", 0);
            }
        }

        int total = videoInfoDao.countVideoListByFlag(videoInfo);
		if(total>0){
			List<VideoInfo> list = videoInfoDao.queryVideoListByFlag(videoInfo);
			for (VideoInfo r : list) {
				if (RedisUtil.isVideoVip(videoInfo.getUserId(), r.getId())) {
					r.setIsVipStatus("1");//有观看权限
				}else {
					r.setIsVipStatus("0");
				}
			}
			//查询poly视频接口相关信息
			for (VideoInfo info : list) {
				PolyInfo polyInfo = RedisUtil.cache(info.getId()+"");
				info.setPolyInfo(polyInfo);

                PolyvTokenUtil tokenUtil = null;
                try {
                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(info.getVideoCode(), info.getAudioCode(),
                            Util.getHostIp(Util.getInetAddress()),
                            videoInfo.getUserId() + "", "123", "1225");
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
                info.setPolyvTokenUtil(tokenUtil);
                info.setVideoCode(null);
                info.setAudioCode(null);
            }
            //用户未完整观看的微课数
			int notSeen = videoInfoDao.queryNotSeen(videoInfo);
			if(null !=list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("not_seen", notSeen);
			}else{
                map.put("err_code", 201);
                map.put("err_msg", "查询失败");
				map.put("rows", null);
			}
		}
		map.put("total", total);
		return map;
	}
	
	@Override
	public Object queryVideoPageByFlag(VideoInfo videoInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", videoInfoDao.countVideoListByFlag(videoInfo));
		map.put("rows", videoInfoDao.queryVideoListByFlag(videoInfo));
		return map;
	}

	@Override
	public Object queryVideoPageDesc(VideoInfo videoInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = videoInfoDao.countVideoPageDesc(videoInfo);
		if(total >0){
			List<VideoInfo> list = videoInfoDao.queryVideoPageDesc(videoInfo);
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
			}else{
				map.put("err_code",-1);
				map.put("err_msg", "查询失败");
				map.put("rows", null);
			}
		}
		map.put("total", total);
		return map;
	}

	@Override
	public Object queryVideoPageByLableName(VideoInfo videoInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
        int total = videoInfoDao.queryVideoCountByLableName(videoInfo);
        map.put("rows", videoInfoDao.queryVideoPageByLableName(videoInfo));
        map.put("total",total);
		return map;
	}

	@Override
    public Object queryVideoInfoById(VideoInfo videoInfo, HttpSession session) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);

//        if (null == loginUser) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户未登录");
//            return map;
//        }
        if (null == loginUser) {
			loginUser = new UserInfo();
			loginUser.setId(0);
		}
        videoInfo.setUserId(loginUser.getId());
        VideoInfo info = videoInfoDao.queryVideoInfoById(videoInfo);

        if (info != null) {
            map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			info.setIsVipStatus("0");
            //【视频免费规则1】七天免费看视频
            long currentTimeStr = new Date().getTime();
            if(null != loginUser.getRegisterDate() && ((currentTimeStr - loginUser.getRegisterDate()) / (60 *60 *24 *1000)) <= 7){
            	info.setIsVipStatus("1");
            	//【服务站规则1: 指定课程包不参与七天免费活动】
            	List<Integer>  cpList = coursePackageVideoRelDao.selectCoursePackageListByVideoId(videoInfo.getId());
            	if(null != cpList && cpList.contains(83)){
            		info.setIsVipStatus("0");
            	}
            }
            
            //【视频免费规则2】活动期间免费
            if("true".equals(WxConsts.IS_VIP_STATUS)){
            	info.setIsVipStatus("1");
            }
            if (RedisUtil.isVideoVip(loginUser.getId(), info.getId())) {
                info.setIsVipStatus("1");
            }
            VideoInfo totalInfo = videoInfoDao.getCountAndPlayTimesByTeacherId(info.getUserId());

            //pc 端
            if (videoInfo.getMessageString() != null && videoInfo.getMessageString().equals("pc")) {
                if (info.getAudioCode() != null) {
                    info.setMessageString("200");//mp3 资源存在
                } else {
                    info.setMessageString("201");//MP3 资源不存在
                }
            } else {
                //
                //map = PolyvUtil.queryUrlByVid(info.getVideoCode());
                //查询poly视频接口相关信息
                PolyvTokenUtil tokenUtil = null;
                try {
                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(info.getVideoCode(), info.getAudioCode(),
                            Util.getHostIp(Util.getInetAddress()),
                            info.getUserId().toString(), "123", "1225");
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                    return "error";
                }

                PolyInfo polyInfo = RedisUtil.cache(info.getId() + "");
                map.put("mpvl", polyInfo.getMpvl());
                map.put("mpvm", polyInfo.getMpvm());
                map.put("mpvh", polyInfo.getMpvh());
                map.put("imgl", polyInfo.getImgl());
                map.put("imgh", polyInfo.getImgh());
                map.put("mpvFlag", polyInfo.getMpvFlag());
                map.put("hls_l", polyInfo.getHls_l());
                map.put("hls_m", polyInfo.getHls_m());
                map.put("hls_h", polyInfo.getHls_h());
                map.put("ts", tokenUtil.getTs());
                map.put("sign", tokenUtil.getSign());

                if (info.getAudioCode() != null) {
                    map.put("mp3", polyInfo.getMp3());
                }
                info.setVideoCode(null);
            }
            map.put("videoInfo", info);
            info.setAudioCode(null);

            if (null != totalInfo) {
                map.put("totalCount", totalInfo.getTotalCount());
                map.put("totalPlayTimes", totalInfo.getPlayTimes());
            }
            return map;
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
		}
		return map;
	}

	@Override
    public Object getVideoListByTeacherId(VideoInfo info, HttpSession session) {
        Map<String,Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }
        info.setTeacherId(info.getUserId());
        info.setUserId(loginUser.getId());
        List<VideoInfo> list = videoInfoDao.getVideoListByTeacherId(info);
		if( null != list && list.size() > 0){
            VideoInfo totalInfo = videoInfoDao.getCountAndPlayTimesByTeacherId(info.getTeacherId());
            if (null != totalInfo) {
				map.put("totalCount", totalInfo.getTotalCount());
				map.put("totalPlayTimes", totalInfo.getPlayTimes());
			}

            for (VideoInfo videoInfo : list) {
                PolyInfo cache = RedisUtil.cache(videoInfo.getId() + "");
                videoInfo.setPolyInfo(cache);

                //会员那层免费的，后端不判断
                if (videoInfo.getFreeFlag() == 0) {
                    Boolean videoVip = RedisUtil.isVideoVip(info.getUserId(), videoInfo.getId());
                    if (videoVip) {
                        videoInfo.setIsVipStatus(1 + "");
                    } else {
                        videoInfo.setIsVipStatus(0 + "");
                    }
                } else {
                    videoInfo.setIsVipStatus(0 + "");
                }
            }
            map.put("err_code", 0);
            map.put("err_msg","查询成功");
			map.put("videoList", list);
			
			return map;
		}else{
			map.put("err_code", 1);
			map.put("err_msg","无数据");
			map.put("videoList", null);
		}
		return map;
	}

	@Override
	public Object getPageVideoByVideoName(VideoInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		int result = videoInfoDao.countVideoByVideoName(info);
		if(result > 0){
			List<VideoInfo> list = videoInfoDao.getPageVideoByVideoName(info);
			map.put("rows", list);
		}
		map.put("total", result);
		return map;
	}

	@Override
	public Object queryVideoCountByLableName(VideoInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		int videoTotalNum = videoInfoDao.queryVideoCountByLableName(info);//某类型下的所有视频数
		if(videoTotalNum > 0){
			int userViewTotalNum = 0 ;
			if (info.getUserId() != null) {
				UserVideoRel rel = new UserVideoRel();
				rel.setUserId(info.getUserId());
				rel.setTypeName(info.getTypeName());
				userViewTotalNum = userVideoRelDao.queryCountByUserIdAndTypeName(rel);
			}
			map.put("err_code", 0);
			map.put("err_msg", "此类型有视频");
			map.put("userViewTotalNum", userViewTotalNum);
			map.put("userNotViewTotalNum", videoTotalNum - userViewTotalNum);
			
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "此类型无相关视频");
		}
		
		return map;
	}

	@Override
	public Object txAddPlayTimes(Integer vid) {
		Map<String,Object> map = new HashMap<String, Object>();
		int count = videoInfoDao.addPlayTimes(vid);
		if (count > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "视频播放次数更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "视频播放次数更新失败");
		}
		return map;
	}

	@Override
	public Object queryPageByPlayTimes(VideoInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		List<VideoInfo> list = videoInfoDao.queryPageByPlayTimes(info);
		int total = videoInfoDao.countList(info);
		if (null !=list && list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "根据播放次数查询成功");
			map.put("rows", list);
			map.put("total", total);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "根据播放次数查询失败");
			map.put("rows", null);
			map.put("total", total);
		}
		return map;
	}

	@Override
	public Object queryPageByFree(VideoInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		List<VideoInfo> list = videoInfoDao.queryPageByFree(info);
		if (null !=list && list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
			map.put("rows", null);
		}
		return map;
	}

	@Override
	public Object selectPageForBackCoursePackage(VideoInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", videoInfoDao.countList(info));
		map.put("rows", videoInfoDao.selectPageForBackCoursePackage(info));
		return map;
	}

	@Override
	public Object queryPageVideo(VideoInfo info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }
        //全站视频数
        int total = videoInfoDao.countList(info);
        if(total >0){
			List<VideoInfo> list = videoInfoDao.queryList(info);
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("total", total);
                map.put("totalCount", total);
                return map;
			}
		}
		map.put("err_code", 1);
		map.put("err_msg", "查询无数据");
        map.put("totalCount", total);
        return map;
	}

	@Override
    public Object exportExl(VideoInfo info, HttpServletResponse response, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<VideoInfo> dataset = videoInfoDao.queryList(info);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");		
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "视频"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, VideoInfo.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public Object txAddClickCount(Integer vid) {
		Map<String,Object> map = new HashMap<String, Object>();
		if (vid==null) {
			map.put("err_code", 400);
			map.put("err_msg", "参数异常");
			return map;
		}
		int count = videoInfoDao.addClickCount(vid);
		if (count > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "视频点击量更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "视频点击量更新失败");
		}
		return map;
	}

	@Override
	public Object updateFinishStatus(VideoInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		if (info.getId()==null||info.getUserId()==null) {
			map.put("err_code", 400);
			map.put("err_msg", "参数异常");
			return map;
		}
		int row = videoInfoDao.updateFinishStatus(info);
		if (row >0) {
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

    @Override
    public Object queryVideoMsgByVids(VideoInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<PolyInfo> list = PolyvUtil.queryVideoMsgByVids(info.getVids());
        if (list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询失败");
        }
        return map;
    }

    //猜你喜欢
    @Override
    public Object queryListForYourFavor(VideoInfo videoInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<VideoInfo> list = videoInfoDao.queryListForYourFavor(videoInfo);
        int count = videoInfoDao.countListForYourFavor(videoInfo);
        if (list != null && list.size() > 0) {
            for (VideoInfo r : list) {
                if (RedisUtil.isVideoVip(videoInfo.getUserId(), r.getId())) {
                    r.setIsVipStatus("1");//有观看权限
                } else {
                    r.setIsVipStatus("0");
                }
            }
            //查询poly视频接口相关信息
            for (VideoInfo info : list) {
                PolyInfo polyInfo = RedisUtil.cache(info.getId() + "");
                info.setPolyInfo(polyInfo);

                PolyvTokenUtil tokenUtil = null;
                try {
                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(info.getVideoCode(), info.getAudioCode(),
                            Util.getHostIp(Util.getInetAddress()),
                            videoInfo.getUserId() + "", "123", "1225");
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
                info.setPolyvTokenUtil(tokenUtil);
                info.setVideoCode(null);
                info.setAudioCode(null);
            }

            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
            map.put("total", count);
        } else {
            return this.queryVideoListByFlag(videoInfo);
        }
        return map;
    }

    //猜你喜欢
    @Override
    public Object queryListForMultiVideoType(CustomModule customModule) {
        Map<String, Object> map = new HashMap<String, Object>();
        customModule.setSortType("notseen");

        String messageString = customModule.getMessageString();
        if (StringUtils.isBlank(messageString)) {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        } else if (messageString.equals("wedding")) {
            customModule.setCmAliasName("婚姻融洽");
        } else if (messageString.equals("body")) {
            customModule.setCmAliasName("自身和谐");
        } else if (messageString.equals("parent_children")) {
            customModule.setCmAliasName("亲子欢乐");
        } else {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        }

        List<VideoInfo> list = videoInfoDao.queryListForMultiVideoType(customModule);

        int hadSeenCount = videoInfoDao.countListForMultiVideoType(customModule);
        customModule.setSortType(null);
        int allCount = videoInfoDao.countListForMultiVideoType(customModule);
        if (list != null && list.size() > 0) {
            for (VideoInfo videoInfo : list) {
                if (RedisUtil.isVideoVip(customModule.getUserId(), videoInfo.getId())) {
                    videoInfo.setIsVipStatus("1");//有观看权限
                } else {
                    videoInfo.setIsVipStatus("0");
                }
            }
            //查询poly视频接口相关信息
            for (VideoInfo videoInfo : list) {
                PolyInfo polyInfo = RedisUtil.cache(videoInfo.getId().toString());
                videoInfo.setPolyInfo(polyInfo);

                PolyvTokenUtil tokenUtil = null;
                try {
                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(videoInfo.getVideoCode(), videoInfo.getAudioCode(),
                            Util.getHostIp(Util.getInetAddress()),
                            customModule.getUserId() + "", "123", "1225");
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
                videoInfo.setPolyvTokenUtil(tokenUtil);
                videoInfo.setVideoCode(null);
                videoInfo.setAudioCode(null);
            }
            float percentage = 1 - new Float(hadSeenCount) / new Float(allCount);
            DecimalFormat fnum = new DecimalFormat("##0.00");
            String percentageStr = fnum.format(percentage);

            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
            map.put("total", hadSeenCount);
            map.put("percentage", percentageStr);
        } else {
            customModule.setSortType(null);
            list = videoInfoDao.queryListForMultiVideoType(customModule);
            hadSeenCount = videoInfoDao.countListForMultiVideoType(customModule);
            customModule.setSortType(null);
            allCount = videoInfoDao.countListForMultiVideoType(customModule);
            if (list != null && list.size() > 0) {
                for (VideoInfo videoInfo : list) {
                    if (RedisUtil.isVideoVip(customModule.getUserId(), videoInfo.getId())) {
                        videoInfo.setIsVipStatus("1");//有观看权限
                    } else {
                        videoInfo.setIsVipStatus("0");
                    }
                }
                //查询poly视频接口相关信息
                for (VideoInfo videoInfo : list) {
                    PolyInfo polyInfo = RedisUtil.cache(videoInfo.getId().toString());
                    videoInfo.setPolyInfo(polyInfo);

                    PolyvTokenUtil tokenUtil = null;
                    try {
                        tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(videoInfo.getVideoCode(), videoInfo.getAudioCode(),
                                Util.getHostIp(Util.getInetAddress()),
                                customModule.getUserId() + "", "123", "1225");
                    } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
                    }
                    videoInfo.setPolyvTokenUtil(tokenUtil);
                    videoInfo.setVideoCode(null);
                    videoInfo.setAudioCode(null);
                }
                float percentage = 1 - new Float(hadSeenCount) / new Float(allCount);
                DecimalFormat fnum = new DecimalFormat("##0.00");
                String percentageStr = fnum.format(percentage);

                map.put("err_code", 0);
                map.put("err_msg", "查询成功");
                map.put("rows", list);
                map.put("total", hadSeenCount);
                map.put("percentage", percentageStr);
            } else {
                map.put("err_code", 201);
                map.put("err_msg", "查询失败");
            }
        }
        return map;
    }

    //分页查询最新,最热课程 根据老师
    @Override
    public Object queryVideoPageDescByUserId(VideoInfo videoInfo, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }

        if (videoInfo.getTeacherId() == null) {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        }
        videoInfo.setUserId(loginUser.getId());
        List<VideoInfo> list = videoInfoDao.queryVideoPageDescByUserId(videoInfo);
        int count = videoInfoDao.countVideoPageDescByUserId(videoInfo);
        if (list != null && list.size() > 0) {
            for (VideoInfo info : list) {
                if (RedisUtil.isVideoVip(loginUser.getId(), info.getId())) {
                    info.setIsVipStatus("1");
                } else {
                    info.setIsVipStatus("0");
                }

                PolyInfo polyInfo = RedisUtil.cache(info.getId() + "");
                info.setPolyInfo(polyInfo);
                info.setAudioCode(null);
                info.setVideoCode(null);
            }

            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
            map.put("total", count);
        } else {
            map.put("err_code", 201);
            map.put("err_msg", "查询失败");
        }
        return map;
    }

}
